"use client";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useState, useEffect } from "react";
import { Asset, getAssets } from "@/lib/api";
import { useRouter } from "next/navigation";
import { ServerIcon, ActivityIcon, WrenchIcon } from "lucide-react";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from "recharts";
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";

export default function Home() {
  const router = useRouter();
  const [assets, setAssets] = useState<Asset[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [totalAssets, setTotalAssets] = useState(0);
  const [activeAssets, setActiveAssets] = useState(0);
  const [maintenanceAssets, setMaintenanceAssets] = useState(0);

  // Fetch assets from backend for statistics
  const fetchAssets = async () => {
    try {
      setLoading(true);
      const data = await getAssets({ 
        page_size: "100" // 获取更多数据用于统计
      });
      setAssets(data.results);
      setTotalAssets(data.count);
      
      // Calculate asset statistics
      const activeCount = data.results.filter(asset => asset.status === 'active').length;
      const maintenanceCount = data.results.filter(asset => asset.status === 'maintenance').length;
      setActiveAssets(activeCount);
      setMaintenanceAssets(maintenanceCount);
      
      setError(null);
    } catch (err) {
      setError("Failed to fetch assets");
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAssets();
  }, []);

  const handleViewAsset = (assetNumber: string) => {
    router.push(`/assets/${assetNumber}`);
  };

  const handleViewAllAssets = () => {
    router.push('/assets');
  };

  // Prepare data for charts
  const statusData = [
    { name: "Active", value: activeAssets },
    { name: "Maintenance", value: maintenanceAssets },
    { name: "Idle", value: totalAssets - activeAssets - maintenanceAssets },
  ];

  const statusChartData = [
    { name: "Active", count: activeAssets },
    { name: "Maintenance", count: maintenanceAssets },
    { name: "Idle", count: totalAssets - activeAssets - maintenanceAssets },
  ];

  const COLORS = ["#10b981", "#f59e0b", "#ef4444"];

  if (loading) {
    return (
      <div className="container mx-auto py-10">
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl font-bold">Dashboard</CardTitle>
            <CardDescription>Loading dashboard...</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 mb-8">
              {[1, 2, 3].map((item) => (
                <Card key={item} className="animate-pulse">
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                    <div className="h-4 bg-gray-200 rounded w-4"></div>
                  </CardHeader>
                  <CardContent>
                    <div className="h-6 bg-gray-200 rounded w-1/2 mb-2"></div>
                    <div className="h-3 bg-gray-200 rounded w-1/3"></div>
                  </CardContent>
                </Card>
              ))}
            </div>
            
            <div className="grid gap-6 md:grid-cols-2 mb-8">
              <Card className="animate-pulse h-80">
                <CardHeader>
                  <div className="h-6 bg-gray-200 rounded w-1/3"></div>
                </CardHeader>
                <CardContent>
                  <div className="h-full bg-gray-200 rounded"></div>
                </CardContent>
              </Card>
              <Card className="animate-pulse h-80">
                <CardHeader>
                  <div className="h-6 bg-gray-200 rounded w-1/3"></div>
                </CardHeader>
                <CardContent>
                  <div className="h-full bg-gray-200 rounded"></div>
                </CardContent>
              </Card>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto py-10">
        <Card className="max-w-2xl mx-auto">
          <CardHeader>
            <CardTitle className="text-3xl font-bold">Dashboard</CardTitle>
            <CardDescription className="text-red-500">{error}</CardDescription>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground">Failed to load dashboard. Please try again later.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-10">
      <Card>
        <CardHeader>
          <CardTitle className="text-3xl font-bold">Dashboard</CardTitle>
          <CardDescription>Overview of your asset management system</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 mb-8">
            <Card className="highlight-card border-l-4 border-l-emerald-500 hover:shadow-lg transition-all duration-200">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Total Assets</CardTitle>
                <ServerIcon className="h-4 w-4 text-emerald-500" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{totalAssets}</div>
                <p className="text-xs text-muted-foreground">+12% from last month</p>
              </CardContent>
            </Card>
            
            <Card className="highlight-card border-l-4 border-l-blue-500 hover:shadow-lg transition-all duration-200">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Active Assets</CardTitle>
                <ActivityIcon className="h-4 w-4 text-blue-500" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{activeAssets}</div>
                <p className="text-xs text-muted-foreground">+5% from last month</p>
              </CardContent>
            </Card>
            
            <Card className="highlight-card border-l-4 border-l-amber-500 hover:shadow-lg transition-all duration-200">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Maintenance</CardTitle>
                <WrenchIcon className="h-4 w-4 text-amber-500" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{maintenanceAssets}</div>
                <p className="text-xs text-muted-foreground">+1 from last week</p>
              </CardContent>
            </Card>
          </div>

          <div className="grid gap-6 md:grid-cols-2 mb-8">
            <Card className="highlight-card hover:shadow-lg transition-all duration-200">
              <CardHeader>
                <CardTitle>Assets by Status</CardTitle>
                <CardDescription>Distribution of assets by their current status</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer config={{}} className="h-80 w-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={statusChartData}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" />
                      <YAxis />
                      <ChartTooltip content={<ChartTooltipContent />} />
                      <Bar dataKey="count" fill="#8884d8">
                        {statusChartData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Bar>
                    </BarChart>
                  </ResponsiveContainer>
                </ChartContainer>
              </CardContent>
            </Card>
            
            <Card className="highlight-card hover:shadow-lg transition-all duration-200">
              <CardHeader>
                <CardTitle>Status Distribution</CardTitle>
                <CardDescription>Percentage breakdown of asset statuses</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer config={{}} className="h-80 w-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={statusData}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        outerRadius={80}
                        fill="#8884d8"
                        dataKey="value"
                        label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                      >
                        {statusData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <ChartTooltip content={<ChartTooltipContent />} />
                    </PieChart>
                  </ResponsiveContainer>
                </ChartContainer>
              </CardContent>
            </Card>
          </div>
          
          <div className="flex justify-between items-center">
            <CardTitle className="text-xl">Recent Assets</CardTitle>
            <div className="space-x-2">
              <button 
                className="text-sm text-muted-foreground hover:text-foreground transition-colors"
                onClick={handleViewAllAssets}
              >
                View all assets →
              </button>
            </div>
          </div>
          
          <div className="mt-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {assets.slice(0, 6).map((asset) => (
              <Card 
                key={asset.id} 
                className="highlight-card cursor-pointer border-l-4 border-l-gray-200 hover:border-l-gray-400 hover:shadow-lg transition-all duration-200"
                onClick={() => router.push(`/assets/${asset.asset_number}`)}
              >
                <CardHeader className="pb-2">
                  <div className="flex justify-between items-start">
                    <CardTitle className="text-lg">{asset.name}</CardTitle>
                    <Badge 
                      variant={
                        asset.status === "active" ? "default" : 
                        asset.status === "maintenance" ? "secondary" : "destructive"
                      }
                      className={
                        asset.status === "active" ? "bg-emerald-100 text-emerald-800" : 
                        asset.status === "maintenance" ? "bg-amber-100 text-amber-800" : "bg-rose-100 text-rose-800"
                      }
                    >
                      {asset.status.charAt(0).toUpperCase() + asset.status.slice(1)}
                    </Badge>
                  </div>
                  <CardDescription className="text-sm">{asset.asset_number}</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div className="flex items-center text-sm">
                      <ServerIcon className="h-4 w-4 mr-2 text-muted-foreground" />
                      <span>
                        {asset.host_info 
                          ? `${asset.host_info.hostname} (${asset.host_info.ip_address})` 
                          : "No host assigned"}
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}